//
//  FileOLPreVIew.swift
//  miaoyin
//
//  Created by David on 2017/3/20.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

class FileOLPreView: UIView, UIWebViewDelegate {

    var delegate: CardViewDelegate?
    
    var titleLabel: UILabel!
    
    var uploadBtn: FCPrintButton!
//    var deleteBtn: FCPrintButton!
    var menuBtn: FCPrintButton!
    
    var webView: UIWebView!
    
    var indexPath: IndexPath?{
        get{
            return uploadBtn.indexPath
        }
        set(i){
            uploadBtn.indexPath = i
//            deleteBtn.indexPath = i
            menuBtn.indexPath = i
        }
    }
    
//    var loadingView: LLFullScreenLoading!
    
    var loadingView: UIActivityIndicatorView!
    var msgView: UILabel!
    
    var fileName: String?
    var fileID: String?
    var filePage: String?
    
    init(frame: CGRect, vc: UIViewController) {
        super.init(frame: frame)
        let bgView = UIVisualEffectView(frame: frame)
        bgView.effect = UIBlurEffect(style: .dark)
        addSubview(bgView)
        
        //        let blankCloseBtn = UIButton(frame: frame)
        //        bgView.addSubview(blankCloseBtn)
        //        blankCloseBtn.addTarget(self, action: #selector(FilePreView.hideView), for: .touchUpInside)
        
        
        
        let cardView = UIView(frame: CGRect(x: 32, y: 0, width: frame.width - 32, height: frame.height - 128))
        cardView.center = CGPoint(x: frame.width/2, y: frame.height/2 + 32)
        cardView.backgroundColor = UIColor.white
        cardView.layer.cornerRadius = 8
        cardView.layer.masksToBounds = true
        bgView.addSubview(cardView)
        
        let titleBar = UIView(frame: CGRect(x: 0, y: 0, width: cardView.frame.width, height: 44))
        cardView.addSubview(titleBar)
        
        let closeBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
        closeBtn.setTitle("×", for: .normal)
        closeBtn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 24)
        closeBtn.setTitleColor(themeColor2, for: .normal)
        titleBar.addSubview(closeBtn)
        closeBtn.addTarget(self, action: #selector(FilePreView.hideView), for: .touchUpInside)
        
        titleLabel = UILabel(frame: CGRect(x: 44, y: 0, width: cardView.frame.width - 88, height: 44))
        titleLabel.text = "文件"
        titleLabel.textAlignment = .center
        titleLabel.lineBreakMode = .byTruncatingMiddle
        titleBar.addSubview(titleLabel)
        
        
        menuBtn = FCPrintButton(frame: CGRect(x: cardView.frame.width - 32, y: 14, width: 20, height: 20))
        menuBtn.setImage(#imageLiteral(resourceName: "menu"), for: .normal)
        titleBar.addSubview(menuBtn)
        
        //        let docVC = QLPreviewController()
        //        docVC.delegate = self
        //        docVC.dataSource = self
        //        addChildViewController(docVC)
        //        docVC.view.frame = CGRect(x: 0, y: 0, width: preView.frame.width, height: preView.frame.height)
        //        preView.addSubview(docVC.view)
        //        docVC.didMove(toParentViewController: self)
        
        webView = UIWebView(frame: CGRect(x: 0, y: 44, width: cardView.frame.width, height: cardView.frame.height - 84))
        webView.delegate = self
        cardView.addSubview(webView)
        webView.scalesPageToFit = true
        
        uploadBtn = FCPrintButton(frame: CGRect(x: 0, y: cardView.frame.height - 44, width: cardView.frame.width, height: 44))
        uploadBtn.backgroundColor = themeColor1
        uploadBtn.setTitle("打印", for: .normal)
        uploadBtn.setTitleColor(UIColor.white, for: .normal)
        uploadBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        cardView.addSubview(uploadBtn)
        
//        deleteBtn = FCPrintButton(frame: CGRect(x: cardView.frame.width/2, y: cardView.frame.height - 44, width: cardView.frame.width/2, height: 44))
//        deleteBtn.backgroundColor = UIColor(red: 192.0/255.0, green: 47.0/255.0, blue: 47.0/255.0, alpha: 1)
//        deleteBtn.setTitle("删除", for: .normal)
//        deleteBtn.setTitleColor(UIColor.white, for: .normal)
//        deleteBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
//        cardView.addSubview(deleteBtn)
        
//        loadingView = LLFullScreenLoading(frame: CGRect(x: 0, y: 0, width: webView.frame.width, height: webView.frame.height))
        loadingView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        loadingView.center = CGPoint(x: frame.width/2, y: frame.height/2)
        webView.addSubview(loadingView)
        
        msgView = UILabel(frame: CGRect(x: 0, y: webView.frame.width, width: webView.frame.width, height: 20))
        msgView.font = UIFont.systemFont(ofSize: 14)
        msgView.textColor = UIColor.lightGray
        msgView.textAlignment = .center
        webView.addSubview(msgView)
        
        alpha = 0
    }
    
    var fileURL: URL?
    
    func openFile(fileName: String?, fileID: String?){
        if fileID == nil{
            return
        }
        titleLabel.text = fileName ?? "文件"
        
        self.uploadBtn.isEnabled = false
        self.uploadBtn.backgroundColor = UIColor.lightGray
        
        msgView.text = ""
        
        webView.loadHTMLString("", baseURL: nil)
        loadingView.alpha = 1
        URLSession.shared.dataTask(with: URL(string: "\(apiBaseDomainName)?m=admin&c=goods&a=filePreview&f=\(fileID!)")!) { (data:
            Data?, re:URLResponse?, er:Error?) in
            do{
                if er != nil{
                    throw er!
                }
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let jsonData = jsonObj?.object(forKey: "data") as? NSDictionary
                let fileURLStr = jsonData?.object(forKey: "url") as? String
                var validURL = false
                if fileURLStr != nil{
                    let url = URL(string: fileURLStr!)
                    if url != nil{
                        validURL = true
                        DispatchQueue.main.async {
                            self.webView.loadRequest(URLRequest(url: url!))
                            self.msgView.text = ""
                            self.uploadBtn.isEnabled = true
                            self.uploadBtn.backgroundColor = themeColor1
                        }
                    }
                }
                
                if !validURL{
                    DispatchQueue.main.async {
                        self.msgView.text = jsonObj?.object(forKey: "message") as? String ?? "文件无法预览"
                    }
                }
                
            }catch let ex{
                DispatchQueue.main.async {
                    self.msgView.text = "文件无法预览，可能正在转码"
                }
                print(ex)
            }
        }.resume()
        
        
        UIView.animate(withDuration: 0.3) {
            self.alpha = 1
        }
    }
    
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        loadingView.alpha = 0
    }
    
    func hideView(){
        delegate?.cardViewClose?(self)
        UIView.animate(withDuration: 0.3) {
            self.alpha = 0
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
